package com.miniapp.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.miniapp.entity.enums.UserTemplateSaveType;
import com.miniapp.dto.MiniUserTemplateInfoDTO;
import com.miniapp.dto.PageDTO;
import com.miniapp.dto.SimpleSearchDTO;
import com.miniapp.entity.*;
import com.miniapp.service.*;
import com.miniapp.utils.BaseUtils;
import com.miniapp.utils.R;
import com.miniapp.utils.RenderHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * 模版表
 *
 * @author linyuchi
 * @email xunli-03@163.com
 * @date 2018-05-20 13:10:34
 */
@RestController
@RequestMapping("/template")
public class MiniTemplateController extends AbstractController {
    @Autowired
    private MiniTemplateService miniTemplateService;

    @Autowired
    private MiniUserTemplateService miniUserTemplateService;

    @Autowired
    private MiniUserProductService miniUserProductService;

    @Autowired
    private MiniUserTemplateInfoService miniUserTemplateInfoService;

    @Autowired
    private MiniAttachmentService miniAttachmentService;

    /**
     * 查询该产品下所有的模版
     */
    @GetMapping("/list")
    public R list(){

        MiniUserProductEntity miniUserProduct = miniUserProductService.findByAppid(this.getAppid());
        List<MiniTemplateEntity> miniTemplateList = miniTemplateService.findByProductId(miniUserProduct.getProductId());
        return R.ok().put("items", miniTemplateList);

    }

    /**
     * 通过用户查询用户拥有的模版列表
     */
    @GetMapping("/user/list")
    public R userList(){
        List<MiniUserTemplateEntity> miniUserTemplates = miniUserTemplateService.findByAppid(this.getAppid());

        return R.ok().put("items",  miniUserTemplates);
    }

    /**
     *  创建新的模版
     */
    @GetMapping("/create/{id}")
    public R create(@PathVariable("id") Long id){

        return miniUserTemplateService.create(id,this.getAppid());
    }


    /**
     * 删除用户模版
     */
    @GetMapping("/delete/{id}")
    public R delete(@PathVariable("id") Long id){

        MiniUserTemplateEntity miniUserTemplate = miniUserTemplateService.getById(id);
        if (!miniUserTemplate.getAppid().equals(this.getAppid())){
            return R.error("该模版属于当前用户");
        }
        miniUserTemplateService.removeById(miniUserTemplate);
        miniUserTemplateInfoService.deleteByTmpId(id);
        return R.ok();
    }
    /**
     * 使用用户模版
     */
    @GetMapping("/use/{id}")
    public R use(@PathVariable("id") Long id){

        MiniUserTemplateEntity miniUserTemplate = miniUserTemplateService.getById(id);
        if (!miniUserTemplate.getAppid().equals(this.getAppid())){
            return R.error("该模版属于当前用户");
        }
        return miniUserTemplateService.use(id,this.getAppid());
    }

    //*****模版页面维护数据*****//

    /**
     * 删除模版页面
     */
    @GetMapping("/delPage/{id}")
    public R delPage(@PathVariable("id") Long id){

        try{
            miniUserTemplateInfoService.removeById(id);
            return R.ok("删除成功！");
        }catch (Exception e){
            return R.error("删除失败！");
        }
    }

    /**
     * 新增页面
     * @return
     */
    @GetMapping("/addPage/{id}")
    public R addPage(@PathVariable("id") Long id){

        try{
            MiniUserTemplateInfoEntity miniUserTemplate = miniUserTemplateInfoService.newInfo(id);
            return R.ok().put("id", miniUserTemplate.getId());
        }catch (Exception e){
            return R.error("新增页面失败！");
        }

    }

    /**
     * 修改用户模版
     */
    @GetMapping("/pagelist")
    public R pageList(){
        SimpleSearchDTO simpleSearchDTO = getSearchDtoFromJqGrid();
        simpleSearchDTO.setExcludeColumns(new String[]{"data","menu_data"});
        simpleSearchDTO.setEntityClass(MiniUserTemplateInfoEntity.class);
        simpleSearchDTO.addSort("home",false);
        List<MiniUserTemplateInfoEntity> list = miniUserTemplateInfoService.findAllBySimpleSearch(simpleSearchDTO);

        return R.ok().put("items",list);
    }
    /**
     * 修改用户模版
     */
    @GetMapping("/pageInfo/{id}")
    public R pageInfo(@PathVariable("id") Long id){

        MiniUserTemplateInfoEntity miniUserTemplate = miniUserTemplateInfoService.getById(id);
        miniUserTemplate.setComList(JSONArray.parseArray(miniUserTemplate.getData()));
        if (BaseUtils.isNotEmpty(miniUserTemplate.getMenuData())){
            miniUserTemplate.setDiyMenu(JSONObject.parseObject(miniUserTemplate.getMenuData()));
        }else {
            miniUserTemplate.setDiyMenu(new JSONObject());
        }
        return R.ok().put("item", miniUserTemplate);
    }
    /**
     * 修改用户模版
     */
    @GetMapping("/templateInfo/{id}")
    public R templateInfo(@PathVariable("id") Long id){

        MiniUserTemplateEntity miniUserTemplate = miniUserTemplateService.getById(id);
        String props = "id,name,imagePath,used,image";
        return R.ok().put("item", RenderHelper.objectChangeToMap(miniUserTemplate,props));
    }
    /**
     * 设置主页
     */
    @GetMapping("{tmpId}/sethome/{id}")
    public R setHome(@PathVariable("tmpId") Long tmpId,@PathVariable("id") Long id){

        MiniUserTemplateInfoEntity miniUserTemplateInfo = miniUserTemplateInfoService.findByUserTmpIdAndHome(tmpId);

//        miniUserTemplateInfoService.setInfoHome(tmpId,id);
        if (BaseUtils.isNotEmpty(miniUserTemplateInfo)){
            miniUserTemplateInfo.setHome(0);
            miniUserTemplateInfoService.updateInfoHome(tmpId);
        }
        MiniUserTemplateInfoEntity miniUserTemplateInfo1 = miniUserTemplateInfoService.getById(id);
        miniUserTemplateInfo1.setHome(1);
        miniUserTemplateInfoService.updateById(miniUserTemplateInfo1);
        return R.ok();
    }



    /**
     * 保存模版
     */
    @RequestMapping("/savePageInfo")
    public R savePageInfo(@RequestBody MiniUserTemplateInfoEntity miniUserTemplateInfo ){

        if (BaseUtils.isEmpty(miniUserTemplateInfo.getId())){
            return R.error("传入数据异常");
        }
        miniUserTemplateInfo.setData(miniUserTemplateInfo.getComList().toJSONString());
        miniUserTemplateInfo.setMenuData(miniUserTemplateInfo.getDiyMenu().toJSONString());
        miniUserTemplateInfoService.saveOrUpdate(miniUserTemplateInfo);

        return R.ok("页面保存成功");
    }
    /**
     * 保存模版
     */
    @RequestMapping("/saveTemplate")
    public R saveTemplate(@RequestBody MiniUserTemplateEntity miniUserTemplate ){


        if (BaseUtils.isEmpty(miniUserTemplate.getId())){
            return R.error("传入数据异常");
        }
        if(miniUserTemplate.getSaveType().equals(UserTemplateSaveType.THIS.getValue())){

            MiniUserTemplateEntity entity = miniUserTemplateService.getById(miniUserTemplate.getId());
            entity.setImagePath(miniUserTemplate.getImagePath());
            entity.setName(miniUserTemplate.getName());
            miniUserTemplateService.updateById(entity);

            return R.ok("模版保存成功");
        }
        return miniUserTemplateService.saveAsTmp(miniUserTemplate);

    }

}
